package ns

import (
	"bufio"
	"encoding/json"
	"k8sbyhasvc/src/k8sstr"
	"log"
	"net/http"
)

type NameSpaceMetadata struct {
	Name string
}

type NameSpaceObject struct {
	Metadata NameSpaceMetadata
	Status   k8sstr.K8SStatus
}
type NameSpace struct {
	Type   string
	Object NameSpaceObject
}

type NameSpaceX struct {
	Host   string
	Prefix string
}

func (ns *NameSpaceX) Init(host string, prefix string) {
	ns.Host = host
	ns.Prefix = prefix
	return
}

func (ns NameSpaceX) Run(ch chan<- NameSpace) {
	resp, err := http.Get(ns.Host + "/" + ns.Prefix + "/watch/namespaces")
	if err != nil {
		log.Fatal("http.Get :", err)
	}
	defer resp.Body.Close()
	bufrd := bufio.NewReader(resp.Body)

	// var buf = make([]byte, 4096)
	var nameSpace NameSpace
	for {
		buf, isPrefix, err := bufrd.ReadLine()
		if err != nil {
			log.Fatal("body read :", err)
		}

		if isPrefix {
			log.Fatal("json is so lajor???")
		}

		// fmt.Println(string(buf))
		json.Unmarshal(buf, &nameSpace)
		// fmt.Println(nameSpace)
		ch <- nameSpace
	}
}
